package com.xy.controller;

import com.xy.dao.DepartmentDao;
import com.xy.dao.EmployeeDao;
import com.xy.pojo.Department;
import com.xy.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao deprecatedDao;


    //跳转list.index，显示全部员工
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    //跳转了添加员工页面
    @GetMapping("/addemp")
    public String addEmpPage(Model model){
        //获取所有部门
        Collection<Department> department = deprecatedDao.getDepartment();
        model.addAttribute("deps",department);
        return "emp/addEmp";
    }

    //添加员工
    @PostMapping("/addemp")
    public String addEmp(Employee employee){
        //System.out.println(employee);
        employeeDao.save(employee);
        //重定到查询
        return "redirect:/emps";
    }

    //跳转修改员工页面，数据反填
    @GetMapping("/updemp/{id}")
    public String toUpdateEmpPage(@PathVariable("id") Integer id,Model model){
        //根据查询员工
        Employee employee = employeeDao.getEmployeeById(id);
        //查询部门列表
        Collection<Department> department = deprecatedDao.getDepartment();
        //存储数据
        model.addAttribute("employee",employee);
        model.addAttribute("deps",department);
        return "emp/updateEmp";
    }

    //修改员工信息
    @PostMapping("/updemp")
    public String updateEmp(Employee employee){
        //使用添加，因为是虚拟数据，map集合，会替换原来的数据
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //根据id删除员工
    @RequestMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
